package com.coda.service.impl;

import com.coda.common.PageResult;
import com.coda.constant.MessageConstant;
import com.coda.constant.RedisKey;
import com.coda.constant.StatusConstant;
import com.coda.context.BaseContext;
import com.coda.exception.BaseException;
import com.coda.mapper.*;
import com.coda.pojo.*;
import com.coda.pojo.dto.WordDTO;
import com.coda.service.WordService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 单词接口实现类
 */
@Service
public class WordServiceImpl implements WordService {

    @Autowired
    private WordMapper wordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DictationResultsMapper dictationResultsMapper;
    @Autowired
    private UserWordDetailMapper userWordDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserWordMapper userWordMapper;
    /**
     * 查询所有单词
     * @return
     */
    @Override
    public PageResult getAllWords(WordDTO wordDTO) {
        //使用分页插件
        PageHelper.startPage(wordDTO.getPage(),wordDTO.getPageSize());
        //查询单词
        Page<Word> wordAll = (Page<Word>) wordMapper.getWordAll(wordDTO);
        //存储分页信息
        PageResult pageResult =new PageResult(wordAll.getTotal(),wordAll.getResult());
        return pageResult;
    }

    /**
     * 获取当前用户已经默写的单词列表
     * @return
     */
    @Override
    public PageResult getDictationList(WordDTO wordDTO) {
        //设置分页参数
        PageHelper.startPage(wordDTO.getPage(),wordDTO.getPageSize());
        //查询单词
        Page<Word> wordPage = (Page<Word>) wordMapper.getWordAllByUserId(wordDTO,BaseContext.getCurrentId());
        //存储分页
        PageResult pageResult = new PageResult(wordPage.getTotal(),wordPage.getResult());
        return pageResult;
    }

    /**
     * 获取需要默写的单词
     * @return
     */
    @Override
    public Word getWord() {
        //获取用户默写位置，根据默写位置查询单词
        User userObj = new User();
        userObj.setId(BaseContext.getCurrentId());
        User user = userMapper.getUser(userObj);
        return wordMapper.getWord(user.getWordIndex()+1);
    }

    /**
     * 匹配默写答案
     * @param id
     * @param word
     * @return
     */
    @Override
    @Transactional
    public int answer(Integer id, String word) {
        //查询默写的单词是否正确
        int result = wordMapper.getWordByIdAndWord(id, word);

        //添加每个单词的默写结果
        DictationResult dictationResult = new DictationResult();
        //从reids中获取当前默写记录的id
        Integer sessionId = (Integer) redisTemplate.opsForValue().get(RedisKey.DICTATION_SESSION_ID);
        if (sessionId == null) {
            throw new BaseException(MessageConstant.DICTATION_ERR);
        }
        //设置默写结果基本信息
        dictationResult.setWordId(id);
        dictationResult.setUserId(BaseContext.getCurrentId());
        dictationResult.setDictationSessionsId(sessionId);
        dictationResult.setUserAnswer(word);
        dictationResult.setCreateTime(LocalDateTime.now());

        //获取用户每个单词的默写详细信息
        UserWordDetail detail = userWordDetailMapper.getuserWordDetail(BaseContext.getCurrentId(),id);
        //如果没有则添加
        if (detail == null) {
            UserWordDetail userWordDetail = new UserWordDetail();
            userWordDetail.setWordId(id);
            userWordDetail.setUserId(BaseContext.getCurrentId());
            userWordDetail.setUpdateTime(LocalDateTime.now());
            userWordDetail.setCorrectCount(0);
            userWordDetail.setInCorrectCount(0);
            userWordDetail.setCreateTime(LocalDateTime.now());
            userWordDetailMapper.insert(userWordDetail);
            //查询刚添加的结果
            detail = userWordDetailMapper.getuserWordDetail(BaseContext.getCurrentId(),id);
        }

        //连续正确次数
        int correctCount = 0;
        //如果正确就添加用户默写单词的位置
        if (result > 0) {
            User user = new User();
            user.setWordIndex(id);
            user.setId(BaseContext.getCurrentId());
            userMapper.update(user);
            //答案正确
            dictationResult.setIsCorrect(StatusConstant.isCorrect);

            //正确次数加一
            detail.setCorrectCount(detail.getCorrectCount()+1);

            //保存当前默写正确的单词 先删除已经有的再插入
            UserWord userWord = new UserWord();
            userWord.setUserId(BaseContext.getCurrentId());
            userWord.setWordId(id);
            userWord.setCreateTime(LocalDateTime.now());
            userWordMapper.delete(userWord);
            userWordMapper.insert(userWord);

            //正确次数+1
            correctCount++;
            //获取用户的连续正确次数
            User u1 = new User();
            u1.setId(BaseContext.getCurrentId());
            User u2 = userMapper.getUser(u1);
            //如果当前连续次数大于用户历史连续次数那么更新
            if (u2 != null && u2.getLongestStreak() != null && u2.getLongestStreak() < correctCount){
                u1.setLongestStreak(correctCount);
                userMapper.update(u1);
            }
        }else {
            //答案错误
            dictationResult.setIsCorrect(StatusConstant.notCorrect);

            //错误次数加1
            detail.setInCorrectCount(detail.getInCorrectCount()+1);

            //归零连续正确次数
            correctCount = 0;
        }
        //添加默写结果
        dictationResultsMapper.insert(dictationResult);
        //添加默写详细信息
        userWordDetailMapper.update(detail);
        return result;
    }

    /**
     * 获取今天默写的单词
     * @param userWord
     * @return
     */
    @Override
    public List<Word> getDailyWord(UserWord userWord) {
        return userWordMapper.getDailyWord(userWord);
    }
}
